package com.itheima.reggie.service.impl;

import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.reggie.common.CustomException;
import com.itheima.reggie.common.ResultInfo;
import com.itheima.reggie.domain.Category;
import com.itheima.reggie.domain.Dish;
import com.itheima.reggie.mapper.CategoryMapper;
import com.itheima.reggie.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

@Service
@Transactional
public class CategoryServiceImpl implements CategoryService {
    @Autowired
   private CategoryMapper categoryMapper;
    @Override
    public List<Category> findAll(){

        return categoryMapper.findAll();
    }
    //新增，保存
    @Override
    public void save(Category category){
        category.setId(IdUtil.getSnowflake(1,1).nextId());

//        //创建时间，修改时间
//        category.setCreateTime(new Date());
//        category.setUpdateTime(new Date());
//
//        category.setCreateUser(1L);
//        category.setUpdateUser(1L);

        //调用service
        categoryMapper.save(category);
    }
    //3.修改，更新
    @Override
    public void update(Category category){
      category.setUpdateUser(1L);
       category.setUpdateTime(new Date());
        //调用service
        categoryMapper.update(category);
    }
    //4.删除内容

    @Override
    public ResultInfo deleteById(Long id){
        //根据菜品id删除
        Integer num1 = categoryMapper.countDishByCategoryId(id);
        if (num1>0){
            throw new CustomException("此类中有菜，不允许删除");

        }
        //统计套餐的数量
        Integer num2 = categoryMapper.countSetmealByCategoryId(id);
        if (num2>0){
            throw new CustomException("此类中有菜，不允许删除");
        }
        categoryMapper.delete(id);
        return ResultInfo.success(null);
    }
    @Override
    public List<Category> findByType(Integer type){
        LambdaQueryWrapper<Category> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Category::getType,type);
        return categoryMapper.selectList(wrapper);
    }



}
